package ua.edu.sumdu.j2se.roman.lab1.controller;

import ua.edu.sumdu.j2se.roman.lab1.domain.TaskList;
import ua.edu.sumdu.j2se.roman.lab1.model.TasksModel;
import ua.edu.sumdu.j2se.roman.lab1.util.Log;

import java.text.SimpleDateFormat;
import java.util.*;
/**
 * Author: Radko Roman.
 */

/**
 * Describes the warning system of the task manager.
 *
 */
public class RemindTimer implements Observer {

    private Timer timer = new Timer();
    private Controller controller;
    private TasksModel model;
    private TimerTask currentTask;

    public RemindTimer(Controller controller, TasksModel model) {
        this.controller = controller;
        this.model = model;
        model.observable().addObserver(this);
        scheduleAction();
    }

    /**
     * Designed to set the timer.
     *
     * @param date  notification date
     * @param tasks all tasks with notification date
     */
    public void scheduleEvent(Date date, final TaskList tasks) {
        currentTask = new TimerTask() {
            @Override
            public void run() {
                controller.tasksTimeBecomeEvent(tasks);
                scheduleAction();
            }
        };
        timer.schedule(currentTask, date);
    }

    /**
     * Finds nearest date from now, gets set of the task with this time and set this time on timer.
     *
     */
    private void scheduleAction() {
        Log.i("scheduleAction was called at: ["+
                new SimpleDateFormat("dd.MM.yy h:mm:ss").format(new Date()) + "]");
        Date firstDate = model.getFirstTaskDateFromNow();
        if (firstDate != null) {
            TaskList firstTasks = model.getTasksByDate(firstDate);
            scheduleEvent(firstDate, firstTasks);
        }
    }

    /**
     * Calls when model have changes.
     *
     * @param o object of observation - model
     */
    @Override
    public void update(Observable o, Object arg) {
        Log.i("Model was updated.");
        if (currentTask != null) {
            currentTask.cancel();
        }
        scheduleAction();
    }
}
